import { defineStore } from "pinia";
// 缓存
import storageFn from '@/utils/storage';

// 保存tag的key
const TAG_KEY = 'Tag-HoldRoutes';

const useLayoutStore: any = defineStore("layout", {
  state: () => {
    return {
        isExpand: false, // 是否展开菜单
        holdRoutes: storageFn.getStorage('session', TAG_KEY) || [
            // 默认首页
            {
              href: '/home',
              resName: '首页',
              resType: 'page',
              component: '/Home/index',
              code: 'projectHome'
            }
        ] as any[],
        isRouterAlive: true, // 是否展示子路由页面（用于刷新路由）
    }
  },
  actions: {
    // 修改是否展开
    handleExpand(isExpand: boolean) {
      this.isExpand = isExpand;
    },
    // 添加路由
    handleAddRoute(route: any) {
        // 首先判断新添加的路由在不在对象中
        const isExist = this.holdRoutes.some((item: any) => item.code == route.code);
        if (!isExist) {
            this.holdRoutes.push(route);
        }
        // 大于10个路由则删除第2个tag
        if (this.holdRoutes.length > 10) {
            this.holdRoutes.splice(1, 1);
        }
        storageFn.setStorage('session', TAG_KEY, this.holdRoutes);
    },
    // 删除指定路由
    handleDeleteRoute(route: any) {
        this.holdRoutes.forEach((item: any, index: number) => {
            if(item.code == route.code) {
              this.holdRoutes.splice(index, 1)
            }
        })
        storageFn.setStorage('session', TAG_KEY, this.holdRoutes);
    },
    // 刷新子路由页面
    refresh() {
        this.isRouterAlive = false
        setTimeout(() => {
          this.isRouterAlive = true
        }, 500)
    },
    // 删除所有路由
    handleDeleteAllRoute() {
      storageFn.removeStorage('session', TAG_KEY);
      this.holdRoutes = [
         // 默认首页
         {
          href: '/home',
          resName: '首页',
          resType: 'page',
          component: '/Home/index',
          code: 'projectHome'
        }
      ];
    },
    // 删除其他路由
    handleDeleteOtherRoute(item: any) {
      this.holdRoutes = [
        // 默认首页
        {
         href: '/home',
         resName: '首页',
         resType: 'page',
         component: '/Home/index',
         code: 'projectHome'
        }
      ]
      // 判断如果是首页下点击的关闭其他，则不push
      const flag = this.holdRoutes.some((val: any) => val.code == item.code);
      if(!flag) {
        this.holdRoutes.push(item);
      }
      storageFn.setStorage('session', TAG_KEY, this.holdRoutes);
    }
  }
});

export default useLayoutStore;
